import {uSelectDevParamList} from '@/api/public'

export const ParamSelect = defineComponent({
  props: {
    value: String,
    devId: {
      type: Number,
      required: true
    },
    lazy: {
      type: Boolean,
      default: true
    }
  },
  emits: {
    'update:value': (str?: string): boolean => true
  },
  setup(props, {emit}) {
    const state = reactive<{
      paramList: SimpleParamData[]
      currentParamCode: string | undefined
    }>({
      currentParamCode: undefined,
      paramList: []
    })

    function getParamList(cb?: (data: SimpleParamData[]) => void) {
      uSelectDevParamList({devId: props.devId})
        .then(res => {
          state.paramList = res.data
          cb && cb(res.data)
        })
        .catch(err => {})
    }

    watch(
      () => props.value,
      n => {
        state.currentParamCode = n
      },
      {immediate: true}
    )

    watch(
      () => state.currentParamCode,
      n => {
        emit('update:value', n)
      }
    )

    onMounted(() => {
      if (!props.lazy)
        getParamList(data => {
          emit('update:value', data[0].paramCode)
        })
    })

    return () => (
      <a-select
        allowClear
        placeholder='下拉选择'
        class={['min-w-100 h-full', (state.currentParamCode ?? null) === null ? 'bg-select' : '']}
        v-model={[state.currentParamCode, 'value']}
        options={state.paramList}
        fieldNames={{
          label: 'paramName',
          value: 'paramCode'
        }}
        onFocus={() => {
          getParamList()
        }}
      ></a-select>
    )
  }
})
